import { useState, useEffect } from 'react'
import { ethers } from 'ethers'
import { CONTRACT_ADDRESS, TOKEN_ADDRESS, BANK_ABI, ERC20_ABI } from '@/config/contracts'

export function useWeb3() {
  const [account, setAccount] = useState('')
  const [bankContract, setBankContract] = useState<ethers.Contract | null>(null)
  const [tokenContract, setTokenContract] = useState<ethers.Contract | null>(null)

  const connectWallet = async () => {
    try {
      if (typeof window.ethereum !== 'undefined') {
        const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' })
        const provider = new ethers.providers.Web3Provider(window.ethereum)
        const signer = provider.getSigner()
        
        setAccount(accounts[0])
        setBankContract(new ethers.Contract(CONTRACT_ADDRESS, BANK_ABI, signer))
        setTokenContract(new ethers.Contract(TOKEN_ADDRESS, ERC20_ABI, signer))
      } else {
        alert('请安装 MetaMask!')
      }
    } catch (error) {
      console.error('连接钱包失败:', error)
    }
  }

  useEffect(() => {
    // 监听账户变化
    if (window.ethereum) {
      window.ethereum.on('accountsChanged', (accounts: string[]) => {
        if (accounts.length > 0) {
          setAccount(accounts[0])
        } else {
          setAccount('')
          setBankContract(null)
          setTokenContract(null)
        }
      })
    }

    return () => {
      if (window.ethereum) {
        window.ethereum.removeListener('accountsChanged', () => {})
      }
    }
  }, [])

  return { account, bankContract, tokenContract, connectWallet }
}
